<script setup>
import { productlst, cate, bannerlist } from "@/services/index";
import { earnCount, skip } from "@/services/user";
import { onShow, onShareAppMessage, onShareTimeline } from "@dcloudio/uni-app";
import { nextTick, ref, watch, onMounted } from "vue";
import tabbarView from "../components/tabbar.vue";
import { useUserStore } from "../../stores/user";
import { userloginStore } from "@/stores/islogin.js";
import { date } from "uview-plus/libs/function/test";
import { formatPrice } from "@/utils/formatPrice";

import imageurl from "../../static/index/home-1.png";
import imageur2 from "../../static/index/home-2.png";
import imageur3 from "../../static/index/home-3.png";
import imageur4 from "../../static/index/home-4.png";
// import { share } from "@/utils/share.js";
const shoplist = ref([
  {
    id: 1,
    name: "标准款",
    icon: imageurl,
  },
  {
    id: 2,
    name: "礼品装",
    icon: imageur2,
  },
  {
    id: 3,
    name: "灸具",
    icon: imageur3,
  },
  {
    id: 3,
    name: "特别款",
    icon: imageur3,
  },
  {
    id: 5,
    name: "特别款",
    icon: imageur3,
  },
]);
const banner = ref();
const content = ref();
const bannerarr = ref([]);
const usercode = ref("");

const popupys = ref(null);

const onVideoEnd = (event) => {
  // 获取 video 组件实例
  const videoContext = uni.createVideoContext("myVideo", this);
  // 重新播放视频
  videoContext.play();
};

//#ifdef H5
uni.hideTabBar();
//#endif
const user = useUserStore();
const userlogin = userloginStore();

const userinfo = ref(null);
const taoll = ref({});
const linkobj = ref({});
const ishowlin = ref(false);

async function getuserdatafun() {
  let userobj = await user.getuserInfo();
  userinfo.value = userobj;
}
const loding = ref(false);
bannerfun();
onShow(() => {
  valuetabbar.value = 0;
  ishowlin.value = false;
  earnCountfun();
  if (user.userInfo) {
    if (user.userInfo && user.userInfo.uid) {
      userlogin.setlogin(true);
    }
    getuserInfogfun();
  } else {
    userinfo.value = {
      name: user.userInfo.name,
      nickname: user.userInfo.nickname,
      phone: user.userInfo.phone,
      level: user.userInfo.level,
      avatar: user.userInfo.avatar,
    };
    usercode.value = user.userInfo.promo_code;
  }
  // catefun();
  productlstfun();
  // #ifdef APP-PLUS
  nextTick(() => {
    if (!uni.getStorageSync("ysxycode")) {
      popupys.value.open("center");
    }
  });
  // #endif
});
getdata();

async function getuserInfogfun() {
  if (uni.getStorageSync("Authorization")) {
    let res = await user.getuserInfo();
    usercode.value = res.promo_code;
  } else {
    usercode.value = "";
  }
}

const selectcateid = ref("");
const selectsubid = ref("");
const selectindex = ref(0);
const selecttwoindex = ref(0);
const goodlist = ref([]);
const shopform = ref({
  page: 1,
  limit: 100,
});

async function catefun() {
  let res = await cate();
  shoplist.value = res.data;
  selectcateid.value = res.data[0].id;
  selectsubid.value = res.data[0].sub[0].id;
  shopform.value.cates = selectsubid.value;
  productlstfun();
}

// #ifdef MP-WEIXIN

onShareAppMessage(() => {
  return {
    title: "膳友会",
    path: "/pages/index/index?referrer_id=" + usercode.value,
    imageUrl: "",
  };
});

// 朋友圈分享
onShareTimeline(() => {
  return {
    title: "膳友会",
    path: "/pages/index/index?referrer_id=" + usercode.value,
    imageUr: "",
  };
});
// #endif
const goselectcate = (id, index) => {
  goodlist.value = [];

  if (selectcateid.value == id) return;
  selectcateid.value = id;
  selectsubid.value =
    shoplist.value[index] &&
    shoplist.value[index].sub &&
    shoplist.value[index].sub[0] &&
    shoplist.value[index].sub[0].id
      ? shoplist.value[index].sub[0].id
      : "";
  selectindex.value = index;
  selecttwoindex.value = 0;
  shopform.value.cates = selectsubid.value;
  productlstfun();
};
const selectcatetwofun = (id, index) => {
  goodlist.value = [];
  if (selectsubid.value == id) return;
  selectsubid.value = id;
  selecttwoindex.value = index;
  shopform.value.cates = selectsubid.value;
  productlstfun();
};

async function productlstfun() {
  loding.value = false;
  let res = await productlst(shopform.value);
  loding.value = true;
  goodlist.value = res.data.list;
}

// onShareAppMessage() {
//       return {
//         title: '标题',
//         path: '页面 path ，必须是以 / 开头的完整路径',
//         imageUrl: '图片',
//       }
//     }
//     // 分享到朋友圈
//     onShareTimeline() {
//       return {
//         title: '标题',
//         path: '页面 path ，必须是以 / 开头的完整路径',
//         imageUrl: '图片',
//       }
//     }

async function bannerfun() {
  let res = await bannerlist();
  bannerarr.value = res.data;
}

const gogoods = (id) => {
  uni.navigateTo({
    url: `/pages/goods/details/index?id=${id}`,
  });
};

async function getdata() {
  // let res = await myIncome({ date: "2024-06" });
}

async function earnCountfun() {
  // let res = await earnCount();
  // taoll.value = res.data;
  // let reslink = await skip();
  // linkobj.value = reslink.data;
  // ishowlin.value = true;
}

// const user = useUserStore();
const statusBarHeight = ref(0);
const menuButtonInfo = ref(null);
const valuetabbar = ref(0);

// 响应式数据
//兼容小程序
// #ifdef MP-WEIXIN
menuButtonInfo.value = uni.getMenuButtonBoundingClientRect();
// #endif

statusBarHeight.value = uni.getSystemInfoSync().statusBarHeight;

// 前往我的客户
const goClientList = () => {
  uni.navigateTo({
    url: "/pages/client/Index",
  });
};

// 前往我的收入
const goIncomeStatistics = () => {
  uni.navigateTo({
    url: "/pages/income-statistics/Index",
  });
};

// 前往推广码
const goProCotionCode = () => {
  uni.navigateTo({
    url: "/pages/promotion-code/Index",
  });
};

// 前往客服
const goContactUs = () => {
  uni.navigateTo({
    url: "/pages/contact-us/Index",
  });
};

// 前往历史业绩
const goIncomeList = () => {
  uni.navigateTo({
    url: "/pages/income-list/Index",
  });
};
//前往我的余额
const goYueEList = () => {
  uni.navigateTo({
    url: "/pages/servicereward/myreward/index",
  });
};

//前往套餐
const goThali = () => {
  uni.navigateTo({
    url: "/pages/thali/upgrade/index",
  });
};
const shareindex = () => {};

// appid="wxbbb8ed3d5b5ada72"
//             username="gh_d08f4ffdf5cc"
//             path="/pages/index/index"

function wxnurl(params, versions) {
  let paramsurl = params ? params : "pages/index/index";
  return `<wx-open-launch-weapp  class="launch-weapp" id="launch-btn" appid="wxbbb8ed3d5b5ada72" username="gh_d08f4ffdf5cc"  path="${paramsurl}" style=" z-index: 99;position: absolute;top: 0; left: 0;display: block;width: 100%;height: 100%;opacity:0;overflow: hidden;" > \<script  type="text/wxtag-template" style="display: block; height: 170px; width: 100%; z-index: 99;opacity:0;"\>\<button style="height: 170px; width: 100%; z-index: 99; display: block"\>点击跳转小程序\<\/button\>\<\/script\></wx-open-launch-weapp>`;
}

const opwx = (url) => {
  let sweixin = null;
  plus.share.getServices(
    (res) => {
      sweixin = res.find((i) => i.id === "weixin");
      if (sweixin) {
        // 分享跳转到微信小程序
        sweixin.launchMiniProgram(
          {
            id: "gh_d08f4ffdf5cc", // 	关联微信小程序的原始ID（"g_"开头的字符串）
            path: url, //	打开小程序的页面路径，不传默认跳转首页
            type: 0, // 	微信小程序版本类型，可取值： 0-正式版； 1-测试版； 2-体验版。 默认值为0。
          },
          (res) => {},
          (err) => {}
        );
      } else {
        // 没有获取到微信分享服务
      }
    },
    (err) => {
      // 获取分享服务列表失败
    }
  );
};

// banner
const bannerconfig = ref({
  indicatorDots: true,
  autoplay: true,
  interval: 2000,
  duration: 500,
  indicatorcolor: "#C3C0BD",
  activecolor: "#ffffff",
});
const taglist = ref([
  {
    id: 1,
    name: "创业加盟",
    icon: imageurl,
    dec: "加入我们一起创业吧",
    url: "/pages/index/list?code=start_join",
  },
  {
    id: 2,
    name: "推广工具",
    dec: "宣传海报生成下载",
    icon: imageur2,
    // url: "/pages/index/list?code=extension_tool",
    url: "/pages/poster/index",
  },
  {
    id: 3,
    name: "产品知识",
    icon: imageur3,
    dec: "养食馆对身体的功效?",
    url: "/pages/index/list?code=product_know",
  },
  {
    id: 4,
    name: "企业介绍",
    icon: imageur4,
    dec: "传统业务线上化",
    url: "/pages/index/list?code=company_profile",
  },
]);

const scrollhei = ref(0);

onMounted(() => {
  nextTick(() => {
    uni
      .createSelectorQuery()
      .select(".home-content")
      .boundingClientRect(function (rect) {
        scrollhei.value = rect.height;
      })
      .exec();
  });
});

const goapayupgrade = () => {
  uni.navigateTo({
    url: "/pages/upgrade/identitylv",
  });
};

const gotagList = (item) => {
  uni.navigateTo({
    url: item.url,
  });
};

const handleDisagree = () => {
  uni.setStorageSync("ysxycode", true);
  popupys.value.close();
};
const handleAgree = () => {
  uni.setStorageSync("ysxycode", true);
  popupys.value.close();
};
</script>

<template>
  <view class="my-content">
    <view class="home-banner" ref="banner">
      <swiper
        class="swiper"
        circular
        :indicator-dots="bannerconfig.indicatorDots"
        :autoplay="bannerconfig.autoplay"
        :interval="bannerconfig.interval"
        :duration="bannerconfig.duration"
        :indicator-color="bannerconfig.indicatorcolor"
        :indicator-active-color="bannerconfig.activecolor"
      >
        <swiper-item
          class="item-banner"
          v-for="(item, index) in bannerarr"
          :key="index"
        >
          <view class="item-banner-view">
            <image :src="item.content" mode="widthFix" />
          </view>
        </swiper-item>
      </swiper>
    </view>

    <view class="home-content" ref="content">
      <view class="home-tag-list home-tag-list-3">
        <view
          class="home-tag-list-item"
          v-for="item in taglist"
          :key="item.id"
          @click="gotagList(item)"
        >
          <view>
            <view class="home-tag-item-img">
              <image :src="item.icon" mode="scaleToFill" />
              <view class="home-tag-item-name">{{ item.name }}</view>
            </view>
            <view class="home-tag-item-title">
              <view>{{ item.dec }}</view>
            </view>
          </view>
        </view>
      </view>
      <!-- @click="goapayupgrade()" -->
      <view class="home-store">
        <!-- <image src="../../static/home/icon-2.png" mode="widthFix" /> -->
        <video
          id="myVideo"
          src="https://cloud.syh8.com/19/b956630a393f8ad04374936cb68fe3.mp4"
          autoplay
          controls
          loop
          onVideoEnd="onVideoEnd"
        />
      </view>

      <view class="shop-good">
        <view
          class="shop-good-item"
          v-for="(item, index) in goodlist"
          :key="index"
          @click="gogoods(item.product_id)"
        >
          <view class="shop-good-item-img">
            <image :src="item.image" mode="aspectFill" />
          </view>
          <view class="shop-good-item-k">
            <view class="shop-good-item-title">
              {{ item.store_name }}
            </view>
          </view>
          <view class="shop-list-price">
            ¥ <text>{{ item.price }}</text></view
          >
        </view>
      </view>
    </view>
  </view>

  <!-- #ifdef MP-WEIXIN || WEB  -->
  <tabbarView :value="valuetabbar"></tabbarView>
  <!-- #endif -->

  <!-- #ifdef MP-WEIXIN -->

  <uni-popup ref="popup" :animation="true" :is-mask-click="false">
    <view class="popup_content">
      <view class="popup_title">
        {{ title }}
      </view>
      <view class="popup_desc">
        {{ desc1 }}
      </view>
      <view class="popup_urlTitle" @click="openPrivacyContract">
        {{ urlTitle }}
      </view>
      <view class="popup_desc">
        {{ desc2 }}
      </view>
      <view class="popup_cz">
        <button
          id="disagree-btn"
          type="default"
          class="weui-btn"
          @click="handleDisagree"
        >
          不同意
        </button>
        <button
          id="agree-btn"
          type="primary"
          open-type="agreePrivacyAuthorization"
          class="weui-btn"
          @agreeprivacyauthorization="handleAgree"
        >
          同意并继续
        </button>
      </view>
    </view>
  </uni-popup>
  <!-- #endif -->
  <!-- #ifdef APP-PLUS -->

  <uni-popup ref="popupys" :animation="true" :is-mask-click="false">
    <view class="popup_content">
      <view class="popup_title">
        {{ "用户协议与隐私政策" }}
      </view>
      <view class="popup_desc">
        {{ "(1)《用户服务协议》中关于个人设备用户信息收集和使用的说明。" }}
      </view>
      <view class="popup_desc">
        {{
          "(2)《隐私政策》中与第三方SDK类服务商数据共享、相关信息收集和使用说明。"
        }}
      </view>
      <view class="popup_desc">
        {{ "用户协议和隐私政策说明:" }}
      </view>
      <br />
      <view class="popup_urlTitle">
        阅读完整的
        <navigator
          url="/pages/mine/userAgreementDeatils?code=user_agree"
          open-type="navigate"
          hover-class="navigator-hover"
          class="popup_url"
        >
          《用户服务协议》
        </navigator>
        与
        <navigator
          url="/pages/mine/userAgreementDeatils?code=privacy_agree"
          open-type="navigate"
          hover-class="navigator-hover"
          class="popup_url"
        >
          《隐私政策》
        </navigator>
        了解 详细信息
      </view>

      <view class="popup_cz">
        <button
          id="disagree-btn"
          type="default"
          class="weui-btn"
          @click="handleDisagree"
        >
          不同意
        </button>
        <button
          id="agree-btn"
          type="primary"
          open-type="agreePrivacyAuthorization"
          class="weui-btn"
          @click="handleAgree"
        >
          同意并继续
        </button>
      </view>
    </view>
  </uni-popup>
  <!-- #endif -->
</template>

<style lang="scss" scoped>
@import "index.scss";
</style>
